# -*- coding: utf-8 -*-
"""
    login decorators
"""

from functools import wraps

from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.utils.http import urlquote

from adrianremembersme import AdrianRemembersMe
from armsettings       import LOGIN_URL

import logging

def login_required( function , redirect_field='next'):
    """
        Enforces that the current view is only acessible to
        logged in users. If not logged, login page is presented
        and after login, redirected to this view.
    """
    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            cookie = request.COOKIES.get('user','')
            member = AdrianRemembersMe().is_logged(cookie_val=cookie)

            if member:
                return view_func(request, *args, **kwargs)

            path        = urlquote( request.get_full_path() )
            login_url   = "%s?%s=%s" % ( LOGIN_URL , redirect_field, path )
            return HttpResponseRedirect(login_url)
        return wraps(view_func)(_wrapped_view)

    return decorator(function)


def login_not_required( function ):
    """
        Forces a view to be public. You can use it as a decorator like::

            @login_not_required
            def myview(request):
                pass

        or on your urls.py file::

            (r'^$', login_not_required(index))


        .. note:: You should also install `RequireLoginMiddleware`,
        	  preferably it should be the last middleware on the chain.
    """
    function.public_page = True
    return function
